package Demo3_13;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-03-13
 * Time:17:08
 */
public class HashBucket {
    //节点数组
    static  class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array=new Node[10];
    public int usedSize;
    public static final float LOAD_FACTOR=0.75f;
    public void put(int key ,int val){
        int index=key% array.length;
        //遍历index数组下的链表，如果遇到相同的key，则更新val
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                cur.val=val;
                return ;
            }else{
                cur=cur.next;
            }
        }
        //头插法
        Node node=new Node(key ,val);
        node.next=array[index];
        array[index]=node;
        usedSize++;
        //3.重新计算当前的负载因子 是不是超过了 我们规定的负载因子
        if(calcLoad_Factor()>=LOAD_FACTOR){
            //扩容
            resize();
        }
    }

    private void resize() {
        Node[] newArray=new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur=array[i];
            while(cur!=null){
                int newIndex=cur.key% newArray.length;
                //把当前节点放到新的数组newIndex位置
                Node curN=cur.next;
                cur.next=newArray[newIndex];
                newArray[newIndex]=cur;
                cur=curN;
            }
        }
        array=newArray;
    }

    private float calcLoad_Factor() {
        return usedSize*1.0f/array.length;
    }
    public int get(int key){
        int index=key%array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;
    }
}
